package com.leonzhangxf.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

/**
 * @author leonzhangxf
 */
public class NioServer {


    public static void main(String[] args) {
        Selector selector = null;
        try {
            selector = Selector.open();

            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress("localhost", 8080));

            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }

        while (true) {
            try {
                selector.select(1000);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey nextKey = null;
                SocketChannel socketChannel = null;
                try {
                    nextKey = keyIterator.next();
                    keyIterator.remove();

                    // handle
                    if (!nextKey.isValid()) {
                        continue;
                    }
                    if (nextKey.isAcceptable()) {
                        System.out.println("server socket accept.");
                        ServerSocketChannel serverSocketChannelFromKey = (ServerSocketChannel) nextKey.channel();
                        try {
                            socketChannel = serverSocketChannelFromKey.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    if (nextKey.isReadable()) {
                        System.out.println("socket read");
                        socketChannel = (SocketChannel) nextKey.channel();
                        readAndWrite(socketChannel);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    if (null != nextKey) {
                        nextKey.cancel();
                    }
                }
            }
        }
    }

    private static void readAndWrite(SocketChannel socketChannel) {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            socketChannel.read(buffer);
            buffer.flip();
            byte[] content = new byte[buffer.remaining()];
            buffer.get(content);
            System.out.println(String.format("read: %s",
                new String(content, StandardCharsets.UTF_8)));
            socketChannel.write(ByteBuffer.wrap("hello 777".getBytes(StandardCharsets.UTF_8)));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
